package com.sanri.tools.modules.mock.l7.http.service.interceptors.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.sanri.tools.modules.mock.data.VarDataMock;
import com.sanri.tools.modules.mock.l7.http.service.dtos.ResponseConfig;
import com.sanri.tools.modules.mock.l7.http.service.interceptors.IntermediateData;
import com.sanri.tools.modules.mock.l7.http.service.interceptors.ResponseInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
@Order(3000)
public class UsingJsMockInterceptor implements ResponseInterceptor {
    @Override
    public boolean match(HttpServletRequest request) {
        final String usingJsMock = request.getParameter("usingJsMock");
        return Boolean.parseBoolean(usingJsMock);
    }

    @Autowired
    private VarDataMock varDataMock;

    @Override
    public void interceptor(ResponseConfig responseConfig, IntermediateData intermediateData, Chain chain) {
        final ResponseConfig.ResponseDetail responseDetail = responseConfig.getResponseDetail();
        final String body = responseDetail.getBody();
        try{
            final JSONObject jsonObject = JSON.parseObject(body);
            varDataMock.mockScript(jsonObject);

            responseDetail.setBody(jsonObject.toJSONString());
        }catch (JSONException e){
            // ignore 当解析失败时, 使用原数据, 有可能并不是 json 数据
        }finally {
            chain.interceptor(responseConfig,intermediateData);
        }
    }
}
